<?php
require_once "Request.php";
require_once "Response.php";
require_once "MessageSystem.php";
require_once "class/char/Creator.php";
/**
 * Parser class, parse requests and responses.
 * @static
 * @package meta
 * @author alcaitiff
 */

class Parser
{
	static private $entryTime;
    /**
     * Process json requests
     * @param array $request Original request array
     * @static
     * @return Request
     */
	static public function jsonRequest($request){
		self::$entryTime  = microtime(true);
		$key		=(isset($request['key']))		?$request['key']		:null;
		$time		=(isset($request['time']))		?$request['time']		:null;
		$id			=(isset($request['id']))		?$request['id']			:null;
		$commands	=(isset($request['command']))	?$request['command']	:array();
		$debug		=(isset($request['debug']))		?$request['debug']		:false;
        if(isset($request['signup']) && $request['signup']=='true'){
            $email		=(isset($request['email']))		?$request['email']		:null;
            $password	=(isset($request['password']))	?$request['password']	:null;
            $charName	=(isset($request['character']))	?$request['character']	:null;
            if($email!=null && $password!=null && $charName!=null){
                $creator=new Creator();
                if(!$creator->register($id, $password, $email, $charName)){
                    MessageSystem::addErrorMessage($creator->message);
                }
            }else{
                MessageSystem::addErrorMessage("Invalid parameters to register");
            }
        }
		if(strtolower($debug)=='false'){
			$debug=false;
		}elseif($debug){
			$debug=true;
		}	
		$responseType=JSON;

		$requestObject = new Request($id,$time,$key,$responseType,$commands,$debug);

		return $requestObject;
	
	}
	
	/**
     * Send a response
     * @param Request $request Request object
     * @return string
     * @static
     */
	static public function sendResponse($request){
		if($request==null){
			$request=new Request();
		}
		$response=new Response($request->player,self::$entryTime);

		if($request->responseType==JSON){
			$response->sendJSON();
		}else
			return 'This response type is not supported yet.';	
	}
}